<?php

namespace app\base\model;

use think\Db;
use think\Model;
use traits\model\SoftDelete;
use think\Config;
use think\Cache;
class Base extends Model
{
    //开启自动写入创建时间与更新时间
    protected $autoWriteTimestamp = true;
    //定义时间戳字段名 int default 0
    protected $createTime = 'created_at';
    protected $updateTime = 'update_at';
    //软删除 引入SoftDelete trait
    use SoftDelete;
    //软删除 字段名称 tinyint  default NULL  1
    protected $deleteTime = 'isdelete';
    public  $BaseExtModel = [];
    public $DeWithExtData = [];
    public $BaseEoror = [  "status"=>0, "msg"=>"异常"];

    protected function initialize(){
        //需要调用model的intitalize方法
        parent::initialize();
        //TODO:自定义的初始化
    }
    /**
     * @param array $where
     * @return $this|int
     * 删除拦截
     */
    public   function delete($where=[],$f=false){
                    if($f){
                        self::where($where)->delete();
                        return 1;
                    }else{
                        if(is_array($where)&&!empty($where)){
                            $d =  self::where($where)->update([$this->deleteTime=>1]);
                            //   echo self::getLastSql();
                            return $d;
                        }
                    }

                    return 0;
    }


    public function trs_pages_join($result){
        //导出excel配置
        $export = w_g("export");
        if($export=="all"){ //导出全部
            foreach($result as $k=>&$v){
                $v = $v->toArray();
            }
            $pageInfo = ['CurrPage' =>0, 'TotalPage' => 0, 'TotalItem' => 0, 'PageSize' => 0];
            return ["res"=>$result,"pageInfo"=>$pageInfo];
        }
        if(is_callable(array($result , 'toArray'))){
            $result = $result->toArray();
            $pageInfo = ['CurrPage' =>$result['current_page'], 'TotalPage' => $result['last_page'], 'TotalItem' => $result['total'], 'PageSize' => $result['per_page']];
            return ["res"=>$result['data'],"pageInfo"=>$pageInfo];
        }

    }

    /**
     * @param $value
     * @return mixed 处理带星 号码的处理
     */
    public function getMobileAttr($value){
        $sid = w_g("sid");
        $row =  Cache::get($sid);

        if(isset($row['is_m_show'])){
            if(!$row['is_m_show']){
                $value = substr_replace($value, '****', 5, 4);
            }
        }
        return $value;
    }

    /**
     *  处理基础模型数据
     */
public function DeWithExtModel(){
        $Files = [];
        $join = [];
        /**
         *  处理方式
         */
    if(!empty($this->BaseExtModel)){
         $data = $this->BaseExtModel;
         foreach($data as $k => $v){
             /**
              *  用户key的处理方案
              */
             if(isset($v['Filed'])){
                 $Filed = keysAddFiles($v['Filed'], $k);
                 array_push($Files, $Filed);
             }
             /**
              *  处理连表操作
              */
             if(isset($v['on'])){
                array_push($join, $v['on']);
             }

         }
     }
            $T_data =  [
                "Files" => !empty($Files)?implode(",",$Files):"",
                "join" => $join,
            ];
        $this->DeWithExtData = $T_data;
        return $T_data;
}
    /**
     * @return array 获取默认的模型链表结构 后台
     */
    public function getExtModel($configName="baseconfig"){
        $configModel = strtolower($this->name);
        if(Config::has($configName.".".$configModel)){
            $data =    Config::get($configName)[$configModel];
        }else{
            $data =  Config::get($configName)['base'];
        }
        $this->BaseExtModel = $data;
    }





    /**
     * @param $where 默认列表输出
     */
    public function defaultPage($where,$Booln=[false,false],$order="a.id asc",$pageSize=15)
    {
        return $this->base_Page($where,isset($pageSize)?$pageSize:15,"a.id asc","baseconfig",true,$Booln);
    }



    /**
     * @param $where 默认列表输出
     */
    public function PcPage($where,$order="a.id asc",$pageSize=15)
    {
        return $this->base_Page($where,$pageSize,$order,"pcconfig");
    }

    /**
     * @param $where 默认列表输出
     * 不去匹配代理商标
     */
    public function AdminPageNoAgent($where,$pageSize=15,$order="a.id asc")
    {
            /**
             *  后台不配置代理商输出
             */
            return $this->base_Page($where,$pageSize,$order,"baseconfig");
    }



    /**
     * @param $where
     * @param int $pageSize
     * @param string $order
     * @param string $config
     * @param bool $agent_search
     * @param array $Booln
     * @return array 默认配置输出结构
     */
    public function base_Page($where,$pageSize=15,$order="a.id asc",$config="baseconfig",$agent_search=false,$Booln=[false,false]){

        $this->getExtModel($config);
        $this->DeWithExtModel();
        $ExtData = $this->DeWithExtData;
        $result = $this->alias("a")
            ->where($where)
            ->order($order)
            ->field(!empty($ExtData['Files']) ? $ExtData['Files'] : "a.*");
        if (!empty($ExtData['join'])) {
            $join = $ExtData['join'];
            if(!empty($join)){
                foreach ($join as $k => $v) {
                    $result->join($v[0], $v[1], isset($v[2])?$v[2]:"left");
                }
            }
        }
        if($agent_search){
            $result = $this->exportExec(trs_resut($result,$Booln[0],$Booln[1]));
        }else{
            $result = $result->paginate(!empty($pageSize)?$pageSize:15);
        }

        return $this->trs_pages_join($result);
    }


        //是否是导出数据处理
  public  function exportExec($result){
      $export = w_g("export");

      if($export=="all"){

         $sql = $result->select(false);

            $res =   Db::query($sql);
            if(!empty($res)){
                exit(json_encode(resJson(1,"导出数据成功",$res)->getData()));
            }else{
                exit(json_encode(resJson(0,"暂无数据")->getData()));
            }


      }





      return $result->paginate();
    }
    //关于用户的操作


    /**
     * @param $where
     * @return int|string 获取数量
     */
    public function baseCount($where){
        return $this->where($where)->count();
    }

    public function getAgentIdNameAttr($value){
        if(!empty($value)){
            $nmodel = new \app\admin\model\AdminAgent();
            $vs=  $nmodel->where("id",$value)->find();
            return isset($vs['agent_name'])?$vs['agent_name']:"暂无";

        }

    }
    public function getStaffIdNameAttr($value){
        if(!empty($value)){

            $nmodel = new \app\admin\model\AdminStaff();
            $vs=  $nmodel->where("id",$value)->find();
            return isset($vs['staff_name'])?$vs['staff_name']:"暂无";

        }
    }
}





